package com.ajieee.merge.config;

import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
import org.apache.hc.core5.ssl.SSLContexts;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestClient;

import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

/**
 * @author ajieee
 * @date 2025-10-02
 */
@Configuration
public class RestConfig {

	@Bean
	public RestClient restClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
		SSLContext sslContext = SSLContexts.custom()
				// 信任所有证书
				.loadTrustMaterial((chain, authType) -> true)
				.build();

		DefaultClientTlsStrategy tlsStrategy = new DefaultClientTlsStrategy(sslContext, (hostname, session) -> true);

		CloseableHttpClient client = HttpClients.custom()
				.setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create()
						.setTlsSocketStrategy(tlsStrategy).build())
				.build();
		return RestClient.builder()
				.requestFactory(new HttpComponentsClientHttpRequestFactory(client))
				.build();
	}

}
